<!--
 * @Descripttion: 空白市场编辑
 * @version: 
 * @Author: lehaixia
 * @Date: 2023-04-26 14:35:17
 * @LastEditors: lehaixia
 * @LastEditTime: 2023-06-16 10:14:24
-->
<template>
  <div class="has-foot-pb">
    <!-- <div class="header">
      <div class="i-top">
        <span class="color-black flex">
          <div class="round"><img src="@/assets/images/store.png" /></div>
          {{ detail.marketName }}</span
        >
      </div>
      <div class="address">
        <img class="icon" src="@/assets/images/position.png" />
        <div class="overLine">
          {{ detail.provinceName }}{{ detail.cityName }}{{ detail.districtName }}{{ detail.streetName }}
        </div>
      </div>
      <div class="tags">{{ getDictName('CITY_LEVEL', detail.cityLevel) }}</div>
    </div> -->
    <Cell
      title="市场名称"
      v-model="formData.marketName"
      required
      divider
      :right="false"
      :isInput="true"
      input-align="right"
      placeholder="输入名称"
    />
    <FieldSelect
      v-model="formData.provinceId"
      title="省份"
      required
      :url="`/app/v1/mdmService/provinces`"
      label-name="name"
      value-name="id"
      method="get"
      clear
      @change="onChangeProvince"
    />
    <FieldSelect
      v-model="formData.cityId"
      title="城市"
      required
      :url="`/app/v1/mdmService/getByParentId/${formData.provinceId}`"
      label-name="name"
      value-name="id"
      method="get"
      :params="{ type: 1 }"
      :parentId="formData.provinceId"
      clear
      mustPid
      @change="onChangeCity"
    />
    <!-- query: { parentId: formData.provinceId }, -->

    <FieldSelect
      v-model="formData.districtId"
      title="区/县"
      :url="`/app/v1/mdmService/getByParentId/${formData.cityId}`"
      label-name="name"
      value-name="id"
      method="get"
      :params="{ type: 1 }"
      :parentId="formData.cityId"
      clear
      mustPid
      @change="onChangeDistricts"
    />

    <FieldSelect
      v-model="formData.streetId"
      title="街道/乡镇"
      :url="`/app/v1/mdmService/getByParentId/${formData.districtId}`"
      label-name="name"
      value-name="id"
      method="get"
      :params="{ type: 1 }"
      :parentId="formData.districtId"
      clear
      mustPid
      @change="onChangeStreet"
    />
    <FieldSelect
      v-model="formData.cityLevel"
      title="城市级别"
      required
      :url="`/data-dict/app/v2/dictionary/CITY_LEVEL`"
      label-name="dictName"
      value-name="dictCode"
      method="get"
      :params="dictParams"
      clear
    />
    <Cell title="所属办事处" :modelValue="detail.agencyName" readonly />
    <!-- 
    <FieldSelect
      v-model="formData.agencyCode"
      v-model:label="formData.agencyName"
      title="所属办事处"
      required
      :url="`/select-service/api/v1/organization/page`"
      label-name="name"
      value-name="code"
      method="post"
      :params="{ query: { isOffice: '1', status: 1 }, type: 0 }"
      clear
    /> -->
    <FieldSelect
      v-model="formData.marketNatrue"
      title="市场属性"
      required
      :url="`/data-dict/app/v2/dictionary/MARKET_NATURE`"
      label-name="dictName"
      value-name="dictCode"
      method="get"
      :includes="['A', 'B', 'C']"
      :params="dictParams"
      clear
    />
    <Cell title="是否有老商家" :custom="true" :right="false">
      <qmp-switch v-model="formData.isOldMerchant" :active-value="1" :inactive-value="0">
        <template #background>
          <span class="qmp-switch__background"> {{ formData.isOldMerchant ? '是' : '否' }}</span>
        </template>
      </qmp-switch>
    </Cell>

    <Cell title="是否遗留问题" :custom="true" :right="false">
      <qmp-switch v-model="formData.isLegacyProblem" :active-value="1" :inactive-value="0">
        <template #background>
          <span class="qmp-switch__background"> {{ formData.isLegacyProblem ? '是' : '否' }}</span>
        </template>
      </qmp-switch>
    </Cell>
    <Cell
      title="遗留问题"
      is-column
      custom
      divider
      :right="false"
      v-if="formData.isLegacyProblem === 1"
      :required="formData.isLegacyProblem === 1"
    >
      <qmp-field v-model="formData.legacyProblemMsg" type="textarea" placeholder="输入内容" class="ctm-text-area" />
    </Cell>
    <Cell title="是否完成招商" :custom="true" :right="false">
      <qmp-switch v-model="formData.isAttractInvestment" :active-value="1" :inactive-value="0">
        <template #background>
          <span class="qmp-switch__background"> {{ formData.isAttractInvestment ? '是' : '否' }}</span>
        </template>
      </qmp-switch>
    </Cell>

    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main" @click="onSubmit">保存</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick } from 'vue'
  import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router'
  import Cell from '@/components/Cell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import { saveItem, detailItem } from '@/apis/attractInvestment/blankMarket'
  import { getDictByPatchType } from '@/apis/dataDict'
  import { initFormData, isChange } from '@/utils'
  import GetKeyboardMixin from '@/utils/useKeyboard'

  interface anyObjectModle {
    id: any
    dictParams: object
    formData: any
    originalData: string
    dictData: any
    detail: any
    submiting: boolean
    isEditBack: boolean
    [key: string]: any
  }
  export default {
    name: 'BlankMarketEdit',
    components: { Cell, FieldSelect },
    setup() {
      const $route = useRoute()
      const $router = useRouter()
      const { proxy }: any = getCurrentInstance()

      const state = reactive<anyObjectModle>({
        id: $route.query.id || '',
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        formData: {
          marketName: '',
          provinceCode: '',
          provinceName: '',
          provinceId: '',
          cityCode: '',
          cityName: '',
          cityId: '',
          districtCode: '',
          districtName: '',
          districtId: '',
          streetCode: '',
          streetName: '',
          streetId: '',
          agencyCode: '',
          agencyName: '',
          cityLevel: '',
          marketNatrue: '',
          isOldMerchant: 0,
          legacyProblemMsg: '',
          isLegacyProblem: 0,
          isAttractInvestment: 0
        },
        originalData: '', // 原始数据 用于对比值是否发生变化
        detail: {},
        dictData: {},
        submiting: false,
        isEditBack: false // 是否是编辑成功后返回
      })
      state.keyboard = {
        show: false
      }
      state.keyboard = GetKeyboardMixin()

      const getDictName = (dictType: string, code: any) => {
        if (!dictType || [undefined, null, ''].includes(code)) return ''
        let name = code
        const dictList = state.dictData[dictType] || []
        if (dictList.length > 0) {
          const obj = dictList.find((v: any) => v.dictCode === `${code}`)
          name = obj?.dictName || code
        }
        return name
      }

      // 获取数据字典
      const getDictData = async () => {
        const dictTypeCodes = ['MARKET_NATURE', 'CITY_LEVEL', 'CTM_MARKET_DATA_FROM']
        state.dictData = await getDictByPatchType({ dictTypeCodes })
      }

      getDictData()

      const getDetail = () => {
        const id = `${state.id}`
        detailItem(id).then((res: any) => {
          state.detail = res.data

          initFormData(res.data, state.formData)
          if ([undefined, null, ''].includes(res.data.isOldMerchant)) state.formData.isOldMerchant = 0
          if ([undefined, null, ''].includes(res.data.isLegacyProblem)) state.formData.isLegacyProblem = 0
          if ([undefined, null, ''].includes(res.data.isAttractInvestment)) state.formData.isAttractInvestment = 0

          state.originalData = JSON.stringify(state.formData)
        })
      }
      getDetail()
      // 阻止返回
      onBeforeRouteLeave((to, from, next) => {
        if (state.isEditBack || isChange(state.formData, state.originalData)) next()
        else {
          proxy.$dialog
            .confirm({
              title: '当前编辑数据未保存，是否确认退出？',
              theme: 'round-button',
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              showCancelButton: true,
              closeOnPopstate: false
            })
            .then(() => {
              next()
            })
            .catch(() => {
              next(false)
            })
        }
      })

      // 省变更
      const onChangeProvince = (data: any) => {
        // console.log(data)

        state.formData.provinceCode = data.code
        state.formData.provinceName = data.name
        state.formData.provinceId = data.id

        state.formData.cityCode = ''
        state.formData.cityName = ''
        state.formData.cityId = ''
        state.formData.districtCode = ''
        state.formData.districtName = ''
        state.formData.districtId = ''
        state.formData.streetCode = ''
        state.formData.streetName = ''
        state.formData.streetId = ''

        state.formData.cityLevel = data.cityLevel || '' // 城市级别
      }
      // 市变更
      const onChangeCity = (data: any) => {
        // console.log(data)
        state.formData.cityCode = data.code
        state.formData.cityName = data.name
        state.formData.cityId = data.id

        state.formData.districtCode = ''
        state.formData.districtName = ''
        state.formData.districtId = ''
        state.formData.streetCode = ''
        state.formData.streetName = ''
        state.formData.streetId = ''

        state.formData.cityLevel = data.cityLevel || '' // 城市级别
      }
      // 区变更
      const onChangeDistricts = (data: any) => {
        // console.log(data)
        state.formData.districtCode = data.code
        state.formData.districtName = data.name
        state.formData.districtId = data.id

        state.formData.streetCode = ''
        state.formData.streetName = ''
        state.formData.streetId = ''

        state.formData.cityLevel = data.cityLevel || '' // 城市级别
      }
      // 街道变更
      const onChangeStreet = (data: any) => {
        // console.log(data)
        state.formData.streetCode = data.code
        state.formData.streetName = data.name
        state.formData.streetId = data.id

        state.formData.cityLevel = data.cityLevel || '' // 城市级别
      }

      const onSubmit = () => {
        // console.log('onSubmit', state.formData)
        if (state.submiting) return
        const data = {
          id: state.id,
          ...state.formData
        }

        if ([undefined, null, ''].includes(data.marketName)) {
          proxy.$toast('请输入市场名称')
          return
        }

        if ([undefined, null, ''].includes(data.provinceCode)) {
          proxy.$toast('请选择省份')
          return
        }

        if ([undefined, null, ''].includes(data.cityCode)) {
          proxy.$toast('请选择城市')
          return
        }

        if ([undefined, null, ''].includes(data.cityLevel)) {
          proxy.$toast('请选择城市级别')
          return
        }

        if ([undefined, null, ''].includes(data.marketNatrue)) {
          proxy.$toast('请选择市场属性')
          return
        }

        if (data.isLegacyProblem === 1 && [undefined, null, ''].includes(data.legacyProblemMsg)) {
          proxy.$toast('请输入遗留问题')
          return
        }
        state.submiting = true
        saveItem(data)
          .then((res: any) => {
            if (res.success === 1) {
              proxy.$toast('编辑成功')
              proxy.$SimpleEvents.emit('refreshCustomerChangeItem')

              nextTick(() => {
                state.isEditBack = true
                $router.goBack()
              })
              state.submiting = false
            }
          })
          .catch((e: any) => {
            if (e) proxy.$toast(e)
            state.submiting = false
          })
      }

      return {
        ...toRefs(state),
        onSubmit,
        getDictName,
        onChangeProvince,
        onChangeCity,
        onChangeDistricts,
        onChangeStreet
      }
    }
  }
</script>

<style lang="less" scoped>
  .header {
    margin: 8px 0;
    padding: 16px 14px;
    background: var(--bg-global-weaker);
    border-radius: 0px 0px 0px 0px;
    .i-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 24px;
      font: var(--font-main-title-strengthen);

      .flex {
        display: flex;
        align-items: center;

        .round {
          width: 24px;
          height: 24px;
          background: var(--texticon-color-warning-normal);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 4px;

          img {
            width: 16px;
            height: 16px;
          }
        }
      }
      .icon {
        width: 24px;
        height: 24px;
        margin-right: 4px;
      }

      .right {
        font: var(--font-main-body);
      }
    }

    .address {
      display: flex;
      align-items: center;
      margin-top: 4px;
      height: 20px;
      margin-bottom: 6px;
      .icon {
        width: 20px;
        height: 20px;
        margin-right: 6px;
      }
    }

    .tags {
      font: var(--font-main-title-strengthen);
      color: var(--texticon-color-warning-normal);
    }
  }
</style>
